//
//  DepoistATMVC.swift
//  d11
//
//  Created by peale on 2018/10/30.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit

class DepoistATMVC: BXBaseVC,UITableViewDelegate,UITableViewDataSource {
    let  reuseIdentifierID : NSString = "DepoistInputItemCell"
    let  reuseIdentifierID2 : NSString = "DepoistSelectCell"
    let  reuseIdentifierID3 : NSString = "DepoistBtnCell"
    let  reuseIdentifierHeadID : NSString = "DepoistHeadView"
    var payCount : Int = 1             //支付通道数量 默认1
    var paySelectIndex : Int = 0         //支付通道选择下标
    var depoistATMDict :[String:Any]? //atm存款数据
    var moneyCount:String? = "" //充值的金额
    var pendingAtm :String = "false" //是否有未提交人工智能提案
    var moneyBtnArray:[String]?
    var submitBtn : UIButton?
    lazy var tableView:UITableView = {
        let table = UITableView(frame:CGRect(x: 0, y: 0, width: self.view.width, height:kScreenHeight-kTabBarBottom-60), style:UITableView.Style.plain)
        table.dataSource = self
        table.delegate = self
        //table.layoutMargins = UIEdgeInsets.zero
        table.separatorStyle = .none
        table.backgroundColor  = UIColor.white
        table.showsVerticalScrollIndicator = false
        table.tableFooterView = UIView.init()
        table.separatorStyle = .none
        table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        table.estimatedRowHeight = 0
        table.estimatedSectionHeaderHeight = 0
        table.estimatedSectionFooterHeight = 0
//        if #available(iOS 11.0, *) {
//            table.contentInsetAdjustmentBehavior = .never
//        } else {
//            self.automaticallyAdjustsScrollViewInsets = false
//        }
        return table
    }()
    
    func initSubmitBtn() -> Void {
        self.submitBtn  = UIButton.init(type: .custom)
        self.submitBtn?.setTitle("提交", for: .normal)
        let layerGradient = CAGradientLayer()
        layerGradient.colors = [
            UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
            UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
        ]
        layerGradient.frame = CGRect(x: 0, y: 0, width: kScreenWidth-20, height: 50)
        self.submitBtn?.layer.addSublayer(layerGradient)
        self.submitBtn?.layer.cornerRadius = 5;
        self.submitBtn?.layer.masksToBounds = true
        self.submitBtn?.addTarget(self, action: #selector(self.actionToSubmit), for: .touchUpInside)
        self.view.addSubview(self.submitBtn!)
        self.submitBtn?.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-20)
            make.height.equalTo(50)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-(kTabBarBottom+10))
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "存款"
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
        self.navigationController?.navigationBar.shadowImage = UIImage()
        
        self.moneyBtnArray = GlobalInfo.moneyButton
        if self.moneyBtnArray == nil {
            self.moneyBtnArray = []
        }
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.tableView)
        self.initSubmitBtn()
        self.automaticallyAdjustsScrollViewInsets = false

    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1{
           return self.payCount
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0{
             return 215
        }else if indexPath.section == 1{
            return 60
        }
        return 80
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if self.payCount != 0 && section == 1{
            var headerView : DepoistHeadView? =  (tableView.dequeueReusableHeaderFooterView(withIdentifier: reuseIdentifierHeadID as String) as? DepoistHeadView)
            if headerView == nil {
                headerView = DepoistHeadView(reuseIdentifier: reuseIdentifierHeadID as String)
            }
            headerView?.setData(title: "支付通道")
            return headerView
        }
        
        return UITableViewHeaderFooterView.init()
        
    }
    
     func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if self.payCount != 0 && section == 1{
            return 40.5
        }
         return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            var cell :DepoistInputItem2Cell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID as String) as? DepoistInputItem2Cell
            if cell == nil {
                cell =  DepoistInputItem2Cell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID as String)
            }
            cell?.callChangeBlock({ (text,type) in
               
                DispatchQueue.main.async {
                    self.moneyCount = text
//                    self.tableView.reloadSections([1], with: UITableView.RowAnimation.automatic)
                }
            })
          let showInfoDict  =  self.depoistATMDict?["showInfo"] as? [String : Any] ?? [:]
           let keyName =  showInfoDict["optionid"] as? String ?? ""
           let dataDict = self.depoistATMDict?[keyName] as? [String : Any] ?? [:]
            cell?.setData(money: self.moneyCount, array: self.moneyBtnArray!,rangeLimit:dataDict["rangeLimit"] as? String ?? "")
            return cell!
        }else if self.payCount != 0 && indexPath.section == 1{
            var cell :DepoistSelectCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID2 as String) as? DepoistSelectCell
            if cell == nil {
                cell =  DepoistSelectCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID2 as String)
            }
            var isBottom = false
            var isSelect = false
            if indexPath.row == self.payCount-1{
                isBottom = true
            }
            if indexPath.row == self.paySelectIndex{
                isSelect = true
            }
            cell?.setData(dict: self.depoistATMDict?["showInfo"] as? [String : Any] ?? [:], isBottom: isBottom, isSelect: isSelect, row: indexPath.row,channel: 1,isBank: false)
            
            return cell!
        }
        return UITableViewCell.init()
//        else{
//            var cell : DepoistBtnCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID3 as String) as? DepoistBtnCell
//            if cell == nil {
//                cell =  DepoistBtnCell(style: UITableViewCellStyle.default, reuseIdentifier: reuseIdentifierID3 as String)
//                cell?.submitBtn?.addTarget(self, action: #selector(self.actionToSubmit),for: .touchUpInside)
//            }
//            return cell!
//        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.payCount != 0 && indexPath.section == 1{
            self.paySelectIndex = indexPath.row
           
            self.tableView.reloadSections([1], with: UITableView.RowAnimation.automatic)
        }
    }
    
   
    //提交信息
    @objc func actionToSubmit() -> Void {
        if self.moneyCount == nil || self.moneyCount == "0" {
            UIHelper.alertSimpleMessage(about: "请输入金额!", withDescription: "", in: self)
            return
        }
        //还需判断金额限制
        self.requestATMInfo()
  
    }
    
    //获取玩家ATM卡讯息
    func requestATMInfo() ->Void {
        if self.paySelectIndex == -1{
            UIHelper.alertSimpleMessage(about: "请选择支付通道!", withDescription: "", in: self)
            return
        }
        let showInfoDict  =  self.depoistATMDict?["showInfo"] as? [String : Any] ?? [:]
        let keyName =  showInfoDict["optionid"] as? String ?? ""
        let dataDict = self.depoistATMDict?[keyName] as? [String : Any] ?? [:]
        let  rangeLimit = dataDict["rangeLimit"] as? String ?? ""
        let limitArray =  rangeLimit.components(separatedBy: ",")
        if limitArray.count >= 1{
            let mindeposit =  limitArray[0]
            if ToolHelper.isPurnFloat(string: mindeposit) == true{
                if Double(self.moneyCount!)! <  Double(mindeposit)!{
                    UIHelper.alertSimpleMessage(about: "金额不能小于\(mindeposit)!", withDescription: "", in: self)
                    return
                }
            }
         
        }
        
        if limitArray.count >= 2{
            let maxdeposit =  limitArray[1]
             if ToolHelper.isPurnFloat(string: maxdeposit) == true{
                if Double(self.moneyCount!)! > Double(maxdeposit)!{
                    UIHelper.alertSimpleMessage(about: "金额不能大于\(maxdeposit)!", withDescription: "", in: self)
                    return
                }
            }
        }

        self.showLoadHUD(title: "")
        NetWorkRequest(API.getATMBankDetailInfo(url: "54855d8", amount: self.moneyCount ?? "0"), completion: { (responseData,statusCode,strData) -> (Void) in
             self.dismissLoadHUD()
            DispatchQueue.main.async {
                let vc = DepoistInfoVC()
                 let dataDict = responseData["data"].dictionary
                vc.bcid = dataDict?["bcid"]?.intValue
                vc.moneyCount = self.moneyCount ?? "0"
                vc.realName = dataDict?["owner"]?.string
                vc.bankNo = dataDict?["card"]?.string
                vc.bankName = dataDict?["name"]?.string
                vc.address = dataDict?["addr"]?.string
                vc.bankCss = dataDict?["css"]?.string
                if vc.bankCss != nil{
                    let totalBankList = GlobalInfo.bankList
                    if totalBankList != nil {
                        for ( _,dict) in (totalBankList?.enumerated())! {
                            if vc.bankCss == dict["logo"] as? String ?? ""{
                                vc.bankicon =  dict["image"] as? String ?? ""
                                break
                            }
                        }
                    }
                }
                 self.navigationController?.pushViewController(vc, animated: true)

            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            self.dismissLoadHUD()
            DispatchQueue.main.async {
                if reCode == "21002"{
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
            }
        }) { () -> (Void) in
            self.dismissLoadHUD()
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "获取银行卡信息异常!", withDescription: "", in: self)
            }
        }
    }
}
